import axios from 'axios';
import config from '../config';

// 创建axios实例
const instance = axios.create({
  baseURL: config.baseURL,
  timeout: config.timeout,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: false // 开发环境禁用credentials
});

// 统一的Token管理
const TokenManager = {
  // 使用标准的key
  getAccessToken: () => localStorage.getItem('access_token'),
  getRefreshToken: () => localStorage.getItem('refresh_token'),
  getUserType: () => localStorage.getItem('user_type'),
  getUserId: () => localStorage.getItem('user_id'),
  
  setTokens: (accessToken, refreshToken, userType = null, userId = null) => {
    localStorage.setItem('access_token', accessToken);
    localStorage.setItem('refresh_token', refreshToken);
    if (userType) localStorage.setItem('user_type', userType);
    if (userId) localStorage.setItem('user_id', userId);
    localStorage.setItem('last_activity', Date.now().toString());
  },
  
  clearTokens: () => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user_type');
    localStorage.removeItem('user_id');
    localStorage.removeItem('last_activity');
    // 兼容旧的key
    localStorage.removeItem('token');
    localStorage.removeItem('role');
  },
  
  updateActivity: () => {
    localStorage.setItem('last_activity', Date.now().toString());
  },
  
  checkSession: () => {
    const lastActivity = localStorage.getItem('last_activity');
    if (lastActivity) {
      const timeDiff = Date.now() - parseInt(lastActivity);
      // 1小时无操作自动登出
      if (timeDiff > 60 * 60 * 1000) {
        TokenManager.clearTokens();
        window.location.href = '/login';
        return false;
      }
    }
    return true;
  },
  
  // 检查是否已登录
  isLoggedIn: () => {
    return !!TokenManager.getAccessToken();
  },
  
  // 获取用户信息
  getUserInfo: () => {
    return {
      accessToken: TokenManager.getAccessToken(),
      refreshToken: TokenManager.getRefreshToken(),
      userType: TokenManager.getUserType(),
      userId: TokenManager.getUserId()
    };
  }
};

// 定期检查会话状态
setInterval(() => {
  if (TokenManager.getAccessToken()) {
    TokenManager.checkSession();
  }
}, 5 * 60 * 1000); // 每5分钟检查一次

// 刷新token的标志，防止多个请求同时刷新
let isRefreshing = false;
let failedQueue = [];

const processQueue = (error, token = null) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error);
    } else {
      prom.resolve(token);
    }
  });
  
  failedQueue = [];
};

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 更新用户活跃时间
    TokenManager.updateActivity();
    
    // 对于注册相关的接口，不添加Authorization头
    const noAuthUrls = [
      '/api/user/sendCode',
      '/api/student/register', 
      '/api/enterprise/register',
      '/api/student/login',
      '/api/enterprise/login',
      '/api/user/verify-email',
      '/api/api/auth/register',
      '/api/api/auth/verify-email',
      '/api/api/auth/resend-verification',
      '/api/api/auth/forgot-password',
      '/api/api/auth/reset-password',
      '/api/codeuser/user/check-email-status',
      '/api/policy/agreement',
      '/api/policy/privacy'
    ];
    
    const shouldAddAuth = !noAuthUrls.some(url => config.url?.includes(url));
    
    // 添加access token到请求头
    const token = TokenManager.getAccessToken();
    if (token && shouldAddAuth) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    // 检查响应的Content-Type
    const contentType = response.headers['content-type'] || response.headers['Content-Type'] || '';
    
    // 如果是JSON响应，直接返回data
    if (contentType.includes('application/json')) {
      return response.data;
    }
    
    // 如果不是JSON响应，尝试解析为JSON
    try {
      const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
      return data;
    } catch (error) {
      return response.data;
    }
  },
  async error => {
    const originalRequest = error.config;
    
    // 检查是否是注册相关的API调用，这些调用不应该触发401跳转
    const isRegistrationApi = originalRequest.url?.includes('/api/user/sendCode') || 
                              originalRequest.url?.includes('/api/student/register') || 
                              originalRequest.url?.includes('/api/enterprise/register');
    
    // 处理401错误 - token过期
    if (error.response?.status === 401 && !originalRequest._retry) {
      // 如果是注册相关的API，不进行token刷新和跳转
      if (isRegistrationApi) {
        return Promise.reject(error);
      }
      
      if (isRefreshing) {
        // 如果正在刷新token，将请求加入队列
        return new Promise((resolve, reject) => {
          failedQueue.push({ resolve, reject });
        }).then(token => {
          originalRequest.headers.Authorization = `Bearer ${token}`;
          return instance(originalRequest);
        }).catch(err => {
          return Promise.reject(err);
        });
      }
      
      originalRequest._retry = true;
      isRefreshing = true;
      
      const refreshToken = TokenManager.getRefreshToken();
      
      if (refreshToken) {
        try {
          // 使用refresh token获取新的access token
          const response = await axios.post(`${config.baseURL}/api/api/v1/refresh-token`, {
            refresh_token: refreshToken
          });
          
          const { access_token, refresh_token: newRefreshToken } = response.data.data;
          TokenManager.setTokens(access_token, newRefreshToken || refreshToken);
          
          // 处理队列中的请求
          processQueue(null, access_token);
          
          // 重试原始请求
          originalRequest.headers.Authorization = `Bearer ${access_token}`;
          return instance(originalRequest);
          
        } catch (refreshError) {
          // refresh token也过期了，清除所有token并跳转登录页
          processQueue(refreshError, null);
          TokenManager.clearTokens();
          window.location.href = '/login';
          return Promise.reject(refreshError);
        } finally {
          isRefreshing = false;
        }
      } else {
        // 没有refresh token，直接跳转登录页
        TokenManager.clearTokens();
        window.location.href = '/login';
        return Promise.reject(error);
      }
    }
    
    // 处理其他错误
    if (error.response) {
      // 检查错误响应的Content-Type
      const contentType = error.response.headers['content-type'] || error.response.headers['Content-Type'] || '';
      let errorData = error.response.data;
      
      // 如果不是JSON格式，尝试解析
      if (!contentType.includes('application/json') && typeof errorData === 'string') {
        try {
          errorData = JSON.parse(errorData);
        } catch (parseError) {
          // 解析失败，保持原始数据
        }
      }
      
      switch (error.response.status) {
        case 400:
          break;
        case 403:
          break;
        case 500:
          break;
        default:
          break;
      }
    }
    return Promise.reject(error);
  }
);

export { TokenManager };

export default instance;